const express = require('express');
const path = require('path');
const fs = require('fs');
const multer = require('multer');
const chalk = require("chalk");
const base = require(path.join(__dirname, './base'));
const uploadplug = require(path.join(__dirname, './../service/uploadplug'));
const dataresult = require(path.join(__dirname, './../module/dataresult'));

const router = express.Router();

const upload = multer({ dest: 'upload_tmp/' });

const plugpath_bak = path.join(__dirname, "./../webapp/plugins_bak");
const plugpath = path.join(__dirname, "./../webapp/plugins");


/**上传插件 */
router.post('/upload', upload.any(), async function (req, res, next) {
    let filename = "";
    let dog_file = "";
    /**上传文件 */
    try {
        filename = req.files[0].originalname;
        let suffix = filename.substr(filename.length - 4, filename.length);
        if(suffix!='.dog'){
            dataresult.errorExec({ msg: '请上传标准的 .dog 插件文件' });
            res.send({ "result": { dataresult } });
        }

        dog_file = path.join(plugpath_bak, filename);

        /**如果存在压缩包则删除 */
        if (await fs.existsSync(dog_file)) {
            await fs.unlinkSync(dog_file);
        }
        
        let data = await fs.readFileSync(req.files[0].path)
        await fs.writeFileSync(dog_file, data);

        dataresult.succExec({ "filename": path.join(filename) })
    } catch (err) {
        console.log(chalk.red("[hotdog file] 文件上传失败"));
        console.log(err);
        dataresult.errorExec({ filename: dog_file });
    }
    
    res.send({ "result": { dataresult } });
});


/**校验插件 */
router.get('/check', async function (req, res) {
    let param = req.query;
    let data = {};
    data = await uploadplug.check(param).catch(
        err => {
            console.log(JSON.stringify(err))
        });
    base.send(res,data);
});

/**安装插件 */
router.get('/install', async function (req, res) {
    let param = req.query;
    let data = await uploadplug.install(param).catch(
        err => {
            console.log(JSON.stringify(err))
        });
    base.send(res,data);
});

/**卸载插件 */
router.get('/uninstall', async function (req, res) {
    let param = req.query;
    let plugid = param.id;
    let data = await uploadplug.uninstall(plugid).catch(
        err => {
            console.log(JSON.stringify(err))
        });
    base.send(res,data);
});


//导出该路由
module.exports = router;